#include "chatwindow.h"
#include "ui_chatwindow.h"

chatWindow::chatWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::chatWindow)
{
    ui->setupUi(this);
    //Step1
    server = new QTcpServer(this);
    //Step3
    connect(server,&QTcpServer::newConnection,this,&chatWindow::new_client);

    ui->msgplainTextEdit->installEventFilter(this);

    ui->myWidget->hide();
}

chatWindow::~chatWindow()
{
    delete ui;
}

bool chatWindow::eventFilter(QObject *watched, QEvent *event)
{
    if ( (watched == ui->msgplainTextEdit) && (event->type() == QEvent::MouseButtonPress) )
    {
        callKeyBoard();
        ui->msgplainTextEdit->setFocus();
    }
    else
        return QMainWindow::eventFilter(watched,event);
}

void chatWindow::callKeyBoard()
{
    ui->myWidget->show();
}

void chatWindow::on_listenButton_clicked()
{
    //Step2
    server->listen(QHostAddress::Any,ui->portEdit->text().toUInt());
}

void chatWindow::on_clearButton_clicked()
{
    ui->chatplainTextEdit->clear();
}

void chatWindow::on_sendButton_clicked()
{
    QString msg = ui->msgplainTextEdit->toPlainText();
    socket->write(msg.toUtf8());
    ui->msgplainTextEdit->clear();
}

void chatWindow::read_data()
{
    QString msg = socket->readAll();
    ui->chatplainTextEdit->appendPlainText(msg);
}

void chatWindow::new_client()
{
    //Step4
    socket = server->nextPendingConnection();
    //Step5
    connect(socket,&QTcpSocket::readyRead,this,&chatWindow::read_data);
    QListWidgetItem* item = new QListWidgetItem;
    QString ip = socket->peerAddress().toString();
    ip.remove("::ffff:");
    item->setText(ip);
    ui->listWidget->addItem(item);
}

void chatWindow::on_minButton_clicked()
{
    ui->myWidget->hide();
}
